package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自定义元对象处理器
 * 用于自动填充创建和更新实体时的公共字段
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    //插入操作时的字段填充
    @Override
    public void insertFill(MetaObject metaObject) {
        // 填充创建时间
        this.strictInsertFill(metaObject, "createTime" , Date.class, new Date());
        // 填充创建者ID
        this.strictInsertFill(metaObject, "createBy" , String.class, loadUserId() + "");
    }

    //更新操作时的字段填充
    @Override
    public void updateFill(MetaObject metaObject) {
        // 填充更新时间
        this.strictUpdateFill(metaObject, "updateTime" , Date.class, new Date());
        // 填充更新者ID
        this.strictUpdateFill(metaObject, "updateBy" , String.class, loadUserId() + "");
    }

    //获取当前登录人的ID
    public static Long loadUserId() {
        try {
            // 获取当前登录人
            LoginUser loginUser = SecurityUtils.getLoginUser();
            // 如果loginUser不为空，则获取当前登录人的ID
            if (ObjectUtils.isNotEmpty(loginUser)) {
                return loginUser.getUserId();
            }
            // 如果未登录则返回1L
            return 1L;
        } catch (Exception e) {
            return 1L;
        }
    }
}